package com.superbytecode.redis.wrapper;

import org.springframework.dao.PessimisticLockingFailureException;
import org.springframework.data.redis.cache.CacheStatistics;
import org.springframework.data.redis.cache.CacheStatisticsCollector;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Collections;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * All rights Reserved, Designed By www.super-bytecode.com
 *
 * @ProjectName: superbytecode-beacon
 * @Package: com.superbytecode.framework.redis.annotation
 * @ClassName: RedisExpireCacheWriter
 * @Description: [自定义的RedisCacheWriter]
 * <p>
 * 重写了spring-data-redis中的 DefaultRedisCacheWriter。<br>
 * 1、使用scan命令代替keys命令
 * 在清理缓存时使用了redis的keys命令。该命令存在安全风险，且在公司生产环境是被禁用的。因此重写了这个类，对clean方法进行重写，该用scan命令进行实现。<br>
 * 2、屏蔽了CacheStatistics的缓存命中率等统计功能，原因是相关类不是公共类，而缓存统计功能不影响缓存的正常使用。
 * </p>
 * @Author: [Lance Ting]
 * @Date: 2023/11/21 11:56
 * @Version: V1.0
 * @Copyright: 2023 www.super-bytecode.com Inc. All rights reserved.
 * TODO: 注意,本文件Lance Ting所作,如果转载或使用请标明具体出处!
 * // @see DefaultRedisCacheWriter
 **/
@SuppressWarnings("all")
public class RedisCacheWriter implements org.springframework.data.redis.cache.RedisCacheWriter {
    private final RedisConnectionFactory connectionFactory;
    private final Duration sleepTime;
    private final CacheStatisticsCollector statistics;

    public RedisCacheWriter(RedisConnectionFactory connectionFactory) {
        this(connectionFactory, Duration.ZERO);
    }

    RedisCacheWriter(RedisConnectionFactory connectionFactory, Duration sleepTime) {
        this(connectionFactory, sleepTime, CacheStatisticsCollector.none());
    }

    RedisCacheWriter(RedisConnectionFactory connectionFactory, Duration sleepTime,//
                     CacheStatisticsCollector cacheStatisticsCollector) {
        Assert.notNull(connectionFactory, "ConnectionFactory must not be null!");
        Assert.notNull(sleepTime, "SleepTime must not be null!");
        Assert.notNull(cacheStatisticsCollector, "CacheStatisticsCollector must not be null!");
        this.connectionFactory = connectionFactory;
        this.sleepTime = sleepTime;
        this.statistics = cacheStatisticsCollector;
    }


    @Override
    public void put(@NonNull String name, @NonNull byte[] key, @NonNull byte[] value,// 
                    @Nullable Duration ttl) {
        Assert.notNull(name, "Name must not be null!");
        Assert.notNull(key, "Key must not be null!");
        Assert.notNull(value, "Value must not be null!");
        // 过期时间
        Duration expiredTime = getExpiredTime(ttl);
        execute(name, connection -> {
            if (shouldExpireWithin(expiredTime)) {
                Expiration expiration = Expiration.from(expiredTime.toMillis(), TimeUnit.MILLISECONDS);
                connection.set(key, value, expiration, RedisStringCommands.SetOption.upsert());
            } else {
                connection.set(key, value);
            }
            return "OK";
        });
        statistics.incPuts(name);
    }

    @Override
    public byte[] get(@NonNull String name, @NonNull byte[] key) {
        Assert.notNull(name, "Name must not be null!");
        Assert.notNull(key, "Key must not be null!");
        byte[] result = execute(name, connection -> connection.get(key));
        statistics.incGets(name);
        if (Objects.nonNull(result)) {
            statistics.incHits(name);
        } else {
            statistics.incMisses(name);
        }
        return result;
    }

    @Override
    public byte[] putIfAbsent(@NonNull String name, @NonNull byte[] key, @NonNull byte[] value,//
                              Duration ttl) {
        Assert.notNull(name, "Name must not be null!");
        Assert.notNull(key, "Key must not be null!");
        Assert.notNull(value, "Value must not be null!");
        Duration expiredTime = getExpiredTime(ttl);
        return execute(name, connection -> {
            if (isLockingCacheWriter()) {
                tryLock(name, connection);
            }
            try {
                Boolean put;
                if (shouldExpireWithin(expiredTime)) {
                    put = connection.set(key, value, Expiration.from(expiredTime), RedisStringCommands.SetOption.ifAbsent());
                } else {
                    put = connection.setNX(key, value);
                }

                if (Boolean.TRUE.equals(put)) {
                    statistics.incPuts(name);
                    return null;
                }
                return connection.get(key);
            } finally {
                if (isLockingCacheWriter()) {
                    tryLock(name, connection);
                }
            }
        });
    }

    @Override
    public void remove(@NonNull String name, @NonNull byte[] key) {
        Assert.notNull(name, "Name must not be null!");
        Assert.notNull(key, "Key must not be null!");
        execute(name, connection -> connection.del(key));
        statistics.incDeletes(name);
    }

    @Override
    public void clean(@NonNull String name, @NonNull byte[] pattern) {
        Assert.notNull(name, "Name must not be null!");
        Assert.notNull(pattern, "Pattern must not be null!");
        execute(name, connection -> {
            boolean wasLocked = false;
            try {
                if (isLockingCacheWriter()) {
                    tryLock(name, connection);
                    wasLocked = true;
                }
                byte[][] keys = Optional.ofNullable(connection.keys(pattern))//
                        .orElse(Collections.emptySet())//
                        .toArray(new byte[0][]);
                if (keys.length > 0) {
                    statistics.incDeletesBy(name, keys.length);
                    connection.del(keys);
                }
            } finally {
                if (wasLocked && isLockingCacheWriter()) {
                    tryUnlock(name, connection);
                }
            }
            return "OK";
        });
    }

    @Override
    @NonNull
    public CacheStatistics getCacheStatistics(@NonNull String cacheName) {
        return statistics.getCacheStatistics(cacheName);
    }

    @Override
    public void clearStatistics(@NonNull String name) {
        statistics.reset(name);
    }

    @Override
    @NonNull
    public org.springframework.data.redis.cache.RedisCacheWriter withStatisticsCollector(@NonNull CacheStatisticsCollector cacheStatisticsCollector) {
        return new RedisCacheWriter(connectionFactory, sleepTime, cacheStatisticsCollector);
    }

    // ----------------------------------------------------------------------
    private <T> T execute(String name, Function<RedisConnection, T> callback) {
        try (RedisConnection connection = connectionFactory.getConnection()) {
            checkAndPotentiallyWaitUntilUnlocked(name, connection);
            return callback.apply(connection);
        }
    }

    private static boolean shouldExpireWithin(@Nullable Duration ttl) {
        return Objects.nonNull(ttl) && !ttl.isZero() && !ttl.isNegative();
    }

    private static byte[] createCacheLockKey(String name) {
        return (name + "~lock").getBytes(StandardCharsets.UTF_8);
    }

    private void checkAndPotentiallyWaitUntilUnlocked(String name, RedisConnection connection) {
        if (!isLockingCacheWriter()) {
            return;
        }
        long lockWaitTimeNs = System.nanoTime();
        try {
            while (tryExists(name, connection)) {
                Thread.sleep(sleepTime.toMillis());
            }
        } catch (InterruptedException ex) {
            // Re-interrupt current thread, to allow other participants to react.
            Thread.currentThread().interrupt();
            throw new PessimisticLockingFailureException(String.format("Interrupted while waiting to unlock cache %s", name), ex);
        } finally {
            statistics.incLockTime(name, System.nanoTime() - lockWaitTimeNs);
        }
    }

    private boolean tryExists(String name, RedisConnection connection) {
        return Objects.equals(connection.exists(createCacheLockKey(name)), Boolean.TRUE);
    }

    private void tryLock(String name, RedisConnection connection) {
        connection.setNX(createCacheLockKey(name), new byte[0]);
    }

    private void tryUnlock(String name, RedisConnection connection) {
        connection.del(createCacheLockKey(name));
    }


    /**
     * @return {@literal true} if {@link org.springframework.data.redis.cache.RedisCacheWriter} uses locks.
     */
    private boolean isLockingCacheWriter() {
        return !sleepTime.isZero() && !sleepTime.isNegative();
    }

    private Duration getExpiredTime(Duration ttl) {
        Long cacheExpire = RedisCacheExpireHolder.getCacheExpire();
        Duration expiredTime = Objects.nonNull(cacheExpire) ? Duration.ofMillis(cacheExpire) : ttl;
        Assert.notNull(expiredTime, "ExpiredTime must not be null!");
        return expiredTime;
    }
}